package com.qd.core.config;

import com.qd.core.security.filter.JwtAuthenticationTokenFilter;
import com.qd.core.security.handle.AuthenticationEntryPointImpl;
import com.qd.core.security.handle.LogoutSuccessHandlerImpl;
import com.qd.core.security.provider.NoPwdDaoAuthenticationProvider;
import com.qd.core.security.provider.WxAuthenticationProvider;
import com.qd.core.service.user.AccountUserDetailsServiceImpl;
import com.qd.core.service.user.WxUserDetailServiceImpl;
import com.qd.system.config.AdminConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.web.filter.CorsFilter;

import java.util.ArrayList;
import java.util.List;

/**
 * spring security配置
 *
 * @author sjk
 * Spring Security默认是停用注解的，要想开启注解，
 * 需要在继承WebSecurityConfigurerAdapter的类上加@EnableGlobalMethodSecurity注解，
 * 并在该类中将AuthenticationManager定义为Bean
 * 开启@Secured 注解过滤权限
 */
@Configuration
@Order(1)
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@RequiredArgsConstructor
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@Slf4j
public class WebSecurityConfig {
    private final AdminConfig adminConfig;
    /**
     * 自定义用户认证逻辑
     */
    private final AccountUserDetailsServiceImpl accountUserDetailsService;
    private final WxUserDetailServiceImpl wxUnionIdDetailsService;
    /**
     * 认证失败处理类
     */
    private final AuthenticationEntryPointImpl unauthorizedHandler;
    /**
     * 退出处理类
     */
    private final LogoutSuccessHandlerImpl logoutSuccessHandler;
    /**
     * token认证过滤器
     */
    private final JwtAuthenticationTokenFilter authenticationTokenFilter;
    /**
     * 跨域过滤器
     */
    private final CorsFilter corsFilter;


    /**
     * 获取AuthenticationManager（认证管理器），登录时认证使用
     */
    @Bean
    public AuthenticationManager authenticationManager() {
        List<AuthenticationProvider> authenticationProviderList = new ArrayList<>();
        authenticationProviderList.add(getDaoAuthenticationProvider());
        authenticationProviderList.add(getWxAuthenticationProvider());
        authenticationProviderList.add(getNoPwdDaoAuthenticationProvider());
        return new ProviderManager(authenticationProviderList);
    }

//    /**
//     * 配置直接放行的url地址
//     */
//    @Bean
//    WebSecurityCustomizer webSecurityCustomizer() {
//        return web -> web.ignoring().antMatchers(getExceptUrl())
//                .antMatchers(
//                        HttpMethod.GET,
//                        "/",
//                        "/*.html",
//                        "/**/*.html",
//                        "/**/*.css",
//                        "/**/*.js",
//                        "/profile/**"
//                )
//                .antMatchers("/profile/**")
//                .antMatchers("/common/download**")
//                .antMatchers("/common/download/resource**")
//                .antMatchers("/swagger-ui.html")
//                .antMatchers("/swagger-resources/**")
//                .antMatchers("/webjars/**")
//                .antMatchers("/*/api-docs")
//                .antMatchers("/druid/**")
//                .antMatchers("/wxmanager/**");
//    }

    /**
     * anyRequest          |   匹配所有请求路径
     * access              |   SpringEl表达式结果为true时可以访问
     * anonymous           |   匿名可以访问
     * denyAll             |   用户不能访问
     * fullyAuthenticated  |   用户完全认证可以访问（非remember-me下自动登录）
     * hasAnyAuthority     |   如果有参数，参数表示权限，则其中任何一个权限可以访问
     * hasAnyRole          |   如果有参数，参数表示角色，则其中任何一个角色可以访问
     * hasAuthority        |   如果有参数，参数表示权限，则其权限可以访问
     * hasIpAddress        |   如果有参数，参数表示IP地址，如果用户IP和参数匹配，则可以访问
     * hasRole             |   如果有参数，参数表示角色，则其角色可以访问
     * permitAll           |   用户可以任意访问
     * rememberMe          |   允许通过remember-me登录的用户访问
     * authenticated       |   用户登录后可访问
     */
    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
//        httpSecurity.authenticationProvider(getDaoAuthenticationProvider())
//                .authenticationProvider(getWxAuthenticationProvider());
        httpSecurity
                // CSRF停用，因为不使用session
                .csrf().disable()
                // 认证失败处理类
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                // 基于token，所以不需要session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                // 过滤请求
                .authorizeRequests()
                // 对于登录login 注册register 验证码captchaImage 允许匿名访问
                .antMatchers(getExceptUrl()).permitAll()
                .antMatchers(
                        HttpMethod.GET,
                        "/",
                        "/*.html",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js",
                        "/profile/**"
                ).permitAll()
                .antMatchers("/profile/**",
                        "/common/download**",
                        "/common/download/resource**",
                        "/swagger-ui.html",
                        "/swagger-resources/**",
                        "/webjars/**",
                        "/*/api-docs",
                        "/druid/**",
                        "/wxmanager/**"
                ).permitAll()
//                .antMatchers("/common/download**").permitAll()
//                .antMatchers("/common/download/resource**").permitAll()
//                .antMatchers("/swagger-ui.html").permitAll()
//                .antMatchers("/swagger-resources/**").permitAll()
//                .antMatchers("/webjars/**").permitAll()
//                .antMatchers("/*/api-docs").permitAll()
//                .antMatchers("/druid/**").permitAll()
//                .antMatchers("/wxmanager/**").permitAll()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated()
                .and()
                .headers().frameOptions().disable();
        httpSecurity.logout().logoutUrl("/sys/userLogin/logout").logoutSuccessHandler(logoutSuccessHandler);
        // 添加JWT filter
        httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        // 添加CORS filter
        httpSecurity.addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class);
        httpSecurity.addFilterBefore(corsFilter, LogoutFilter.class);
        return httpSecurity.build();
    }


    /**
     * 强散列哈希加密实现
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationProvider getDaoAuthenticationProvider() {
        final DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setHideUserNotFoundExceptions(false);
        daoAuthenticationProvider.setUserDetailsService(accountUserDetailsService);
        daoAuthenticationProvider.setPasswordEncoder(bCryptPasswordEncoder());
        return daoAuthenticationProvider;
    }

    @Bean
    public AuthenticationProvider getNoPwdDaoAuthenticationProvider() {
        final NoPwdDaoAuthenticationProvider noPwdDaoAuthenticationProvider = new NoPwdDaoAuthenticationProvider();
        noPwdDaoAuthenticationProvider.setUserDetailsService(accountUserDetailsService);
        return noPwdDaoAuthenticationProvider;
    }

    @Bean
    public AuthenticationProvider getWxAuthenticationProvider() {
        WxAuthenticationProvider provider = new WxAuthenticationProvider();
        provider.setUserDetailsService(wxUnionIdDetailsService);
        return provider;
    }


    /**
     * 必须的配置，否则列外url依然会进入过滤器
     *
     * @param filter 过滤器
     * @return FilterRegistrationBean
     */
    @Bean
    public FilterRegistrationBean<JwtAuthenticationTokenFilter> registration(JwtAuthenticationTokenFilter filter) {
        final FilterRegistrationBean<JwtAuthenticationTokenFilter> registration = new FilterRegistrationBean<>(filter);
        registration.setEnabled(false);
        return registration;
    }

    public String[] getExceptUrl() {
        List<String> exceptUrl = adminConfig.getExceptUrl();
        if (null == exceptUrl || exceptUrl.isEmpty()) {
            exceptUrl = new ArrayList<>();
            exceptUrl.add("/**/login");
            exceptUrl.add("/**/register");
            exceptUrl.add("/**/captchaImage");
        }
        if (log.isDebugEnabled()) {
            exceptUrl.forEach(url -> log.debug("不鉴权url列表: {}", url));
        }
        return exceptUrl.toArray(new String[]{});
    }
}